package com.fowo.api.jm.functions;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fowo.api.common.util.ContextHolder;
import com.fowo.api.config.AppProperties;
import com.fowo.api.jm.JmUtil;
import com.fowo.api.sys.entity.SysFile;
import com.googlecode.aviator.runtime.function.AbstractFunction;
import com.googlecode.aviator.runtime.type.AviatorObject;
import com.googlecode.aviator.runtime.type.AviatorRuntimeJavaType;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 提供用于从附件字段中获取图片地址的函数
 *
 * @author yl_ls
 */
public class FileImageUrlFunction extends AbstractFunction {
    @Resource
    private AppProperties appProperties;
    @Override
    public String getName() {
        return "fileImageUrl";
    }

    @Override
    public AviatorObject call(Map<String, Object> env, AviatorObject arg1) {
        AppProperties appProperties = ContextHolder.getApplicationContext().getBean(AppProperties.class);
        String str = arg1.stringValue(env);
        if (StringUtils.hasText(str)) {
            str = JmUtil.replaceBackChineseDoubleQuotes(str);
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                List<SysFile> files = objectMapper.readValue(str, new TypeReference<List<SysFile>>() {
                });
                if (!files.isEmpty()) {
//                    String url = "/api/file/view/" + files.get(0).getStorageKey();
//                    return AviatorRuntimeJavaType.valueOf(appProperties.addHostUriToPath(url));
                    String url = StrUtil.blankToDefault(appProperties.getSysFilePreivewUrlPrefix(),"/api/file/view/")  + files.get(0).getStorageKey();
                    return AviatorRuntimeJavaType.valueOf(url);
                }
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }

        }
        return AviatorRuntimeJavaType.valueOf(null);
    }
}
